package com.originskyseed.platform.pk.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.pk.i18n.PkResponseMsg;
import com.originskyseed.platform.pk.model.Pk;
import com.originskyseed.platform.pk.model.PkRule;
import com.originskyseed.platform.pk.service.IPkRuleService;
import com.originskyseed.platform.pk.service.IPkService;
import com.originskyseed.platform.pk.vo.request.PkRequestVO;
import com.originskyseed.platform.pk.vo.request.PkRuleRequestVO;
import com.originskyseed.platform.recruit.service.IRecruitRelateRecommendService;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IAnchorRelateLiveService;
import com.originskyseed.platform.user.service.IAnchorService;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IFamilyService;
import com.originskyseed.platform.user.service.IPlayerService;
import com.originskyseed.platform.user.service.ITradeUnionService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * pk信息表Controller类（OSI_PK）
 *
 * @author WuZhuoXi
 */
@Controller
@RequestMapping("/pk")
@BaseLocaleResource(localeFileName = "i18n_pk")
public class PkController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PkController.class);

    @DubboReference
    private IPkService pkService;

    @DubboReference
    private IPkRuleService pkRuleService;

    @DubboReference
    private IFamilyService familyService;

    @DubboReference
    private IAnchorService anchorService;

    @DubboReference
    private ITradeUnionService tradeUnionService;

    @DubboReference
    private IDeptService deptService;

    @DubboReference
    private IUserInfoService userInfoService;

    @DubboReference
    private IPlayerService playerService;

    @DubboReference
    private IAnchorRelateLiveService anchorRelateLiveService;

    @DubboReference
    private IRecruitRelateRecommendService recruitRelateRecommendService;



    /**
     * pk广场分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pkList.json", method = RequestMethod.POST)
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<Pk>> pkList(HttpServletRequest request) {
        BaseResponseBody<BasePage<Pk>> result = null;
        try {
            // 请求对象
            PkRequestVO requestVO = this.getParameterBean(PkRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            if (userInfo.getSourceSys() != 0) {
                requestVO.setIsOw(1);
                if (userInfo.getSourceSys() == 1) {
                    requestVO.setPlatform(1);
                } else {
                    requestVO.setPlatform(2);
                }
            }
            // 分页查询
            BasePage<Pk> page = new BasePage<Pk>(requestVO.getPageNo(), requestVO.getPageSize());
            page = this.pkService.selectListByPage(requestVO.toMap(), page, userInfo);
            result = new BaseResponseBody<BasePage<Pk>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<Pk>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 我的pk分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/myPkList.json", method = RequestMethod.POST)
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<Pk>> myPkList(HttpServletRequest request) {
        BaseResponseBody<BasePage<Pk>> result = null;
        try {
            // 请求对象
            PkRequestVO requestVO = this.getParameterBean(PkRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            requestVO.setIsOw(1);
            // 分页查询
            BasePage<Pk> page = new BasePage<Pk>(requestVO.getPageNo(), requestVO.getPageSize());
            page = this.pkService.selectMyPkListByPage(requestVO.toMap(), page, userInfo);
            result = new BaseResponseBody<BasePage<Pk>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<Pk>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 发起PK规则列表分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pkRuleList.json", method = RequestMethod.POST)
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<PkRule>> pkRuleList(HttpServletRequest request) {
        BaseResponseBody<BasePage<PkRule>> result = null;
        try {
            // 请求对象
            PkRuleRequestVO requestVO = this.getParameterBean(PkRuleRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            requestVO.setSourceSys(userInfo.getSourceSys());
            requestVO.setState(1);
            // 分页查询
            BasePage<PkRule> page = new BasePage<PkRule>(requestVO.getPageNo(), requestVO.getPageSize());
            page = this.pkRuleService.selectPkRuleListByPage(requestVO.toMap(), page);
            result = new BaseResponseBody<BasePage<PkRule>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<PkRule>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 保存信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pkSave.json", method = RequestMethod.POST)
    @RequiredParams(names = {})
    public BaseResponseBody<Pk> pkSave(HttpServletRequest request) {
        BaseResponseBody<Pk> result = null;
        try {
            // 请求对象
            Pk pk = this.getParameterBean(Pk.class);

            if (StringUtils.isNotBlank(pk.getId())) {
                if (pk.getIsReceive() == 1) {
                    pk.setIsRead(1);
                    pk.setState(2);
                }
                if (pk.getIsReceive() == 3) {
                    pk.setIsRead(1);
                    pk.setState(4);//失效
                }
                this.pkService.updateByPrimaryKeySelective(pk);
            } else {
                UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
                if (userInfo.getType() == 6 || userInfo.getType() == 11) {
                    pk.setObjUserId(userInfo.getId());
                    pk.setObjUserName(userInfo.getName());
                    pk.setObjUserType(userInfo.getType());
                    pk.setToUserType(userInfo.getType());
                }/*else {
                    //部门查询
                    Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
                    pk.setObjUserId(dept.getId());
                    pk.setObjUserName(dept.getName());
                }*/
                //指定类型pk
                /*if(pk != null &&(pk.getObjUserId() != null &&StringUtils.isNotBlank(pk.getObjUserId()))){
                    UserInfo userInfo1 = this.userInfoService.selectByPrimaryKey(pk.getObjUserId());
                    if(userInfo1!=null) {
                        pk.setPlatform(userInfo1.getSourceSys());
                    }
                    else
                    {
                        logger.error("=getObjUserId=="+pk.getObjUserId());
                    }
                }*/
                pk.setPlatform(userInfo.getSourceSys());
                pk.setUserType(userInfo.getType());
                pk.setCreator(userInfo.getName());
                pk.setCreatorId(userInfo.getId());
                pk.setResult(4);//还没结果
                pk.setIsReceive(2);//接受pk状态
                pk.setState(1);
                this.pkService.insertSelective(pk);
            }
            result = new BaseResponseBody<Pk>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.SAVE_SUCCESS.getMsg()), pk);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Pk>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 删除信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pkDelete.json", method = RequestMethod.POST)
    @RequiredParams(names = {"ids"})
    public BaseResponseBody<Boolean> pkDelete(HttpServletRequest request) {
        BaseResponseBody<Boolean> result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});

            this.pkService.deleteByPrimaryKeys(Arrays.asList(ids));
            result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DELETE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 详情
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pkDetails.json", method = RequestMethod.POST)
    @RequiredParams(names = {"id"})
    public BaseResponseBody<Pk> pkDetails(HttpServletRequest request) {
        BaseResponseBody<Pk> result = null;
        try {
            // 请求参数
            String id = this.getParameterString("id", null);

            Pk pk = this.pkService.selectByPrimaryKey(id);
            //匿名
            if (pk != null) {
                if (pk.getIsAnonymous() == 1) {
                    pk.setObjUserName("神秘人");
                    pk.setObjUserId("***");
                }
            }
            PkRule pkRule = this.pkRuleService.selectByPrimaryKey(pk.getTypeId());
            pk.setRuleNumber(pkRule.getRuleNumber());
            pk.setRuleTitle(pkRule.getRuleTitle());
            pk.setType(pkRule.getType());
            result = new BaseResponseBody<Pk>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_SUCCESS.getMsg()), pk);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Pk>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), PkResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * pk列表_导出
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/pkListToExcel.json")
    @SysLog(module = "竞技中心", operationDesc = "PK列表信息")
    public void pkListToExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            PkRequestVO requestVO = this.getParameterBean(PkRequestVO.class);
            List<Pk> list = this.pkService.listToExcel(requestVO.toMap());
            // excel标题
            String[] title = {"PK编号", "PK标题", "所属平台", "赌注类型", "发起人", "PK赌注", "PK对象", "PK发起时间", "PK终止时间", "PK对象完成情况", "PK状态", "PK结果"};
            // excel文件名
            String fileName = "pk列表信息" + System.currentTimeMillis() + ".xls";
            // sheet名
            String sheetName = "pk信息";
            String[][] values = new String[list.size()][];
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    values[i] = new String[title.length];
                    Pk obj = list.get(i);
                    values[i][0] = obj.getId();
                    values[i][1] = obj.getRuleTitle() == null ? "" : obj.getRuleTitle();
                    if (obj.getPlatform() != null) {
                        if (obj.getPlatform() == 0) {
                            values[i][2] = "全平台";
                        } else if (obj.getPlatform() == 1) {
                            values[i][2] = "内容平台";
                        } else if (obj.getPlatform() == 2) {
                            values[i][2] = "推广平台";
                        } else {
                            values[i][2] = "";
                        }
                    } else {
                        values[i][2] = "";
                    }
                    //1-主播时长,2-主播人气值,3-优质用户数,4-潜力用户数,5-内荐人数,6-主播心动用户数,7-新用户充值金额,8-用户总充值金额
                    if (obj.getType() != null) {
                        if (obj.getType() == 1) {
                            values[i][3] = "主播时长";
                        } else if (obj.getType() == 2) {
                            values[i][3] = "主播人气值";
                        } else if (obj.getType() == 3) {
                            values[i][3] = "优质用户数";
                        } else if (obj.getType() == 4) {
                            values[i][3] = "潜力用户数";
                        } else if (obj.getType() == 5) {
                            values[i][3] = "内荐人数";
                        } else if (obj.getType() == 6) {
                            values[i][3] = "主播心动用户数";
                        } else if (obj.getType() == 7) {
                            values[i][3] = "新用户充值金额";
                        } else if (obj.getType() == 8) {
                            values[i][3] = "用户总充值金额";
                        } else {
                            values[i][3] = "";
                        }
                    } else {
                        values[i][3] = "";
                    }
                    values[i][4] = obj.getObjUserName() == null ? "" : obj.getObjUserName();
                    values[i][5] = obj.getWager() == null ? "" : obj.getWager();
                    values[i][6] = obj.getToUserName() == null ? "" : obj.getToUserName();
                    values[i][7] = obj.getBeginTime() == null ? "" : format.format(obj.getBeginTime());
                    values[i][8] = obj.getEndTime() == null ? "" : format.format(obj.getEndTime());
                    values[i][9] = obj.getObjUserPerformance() == null ? "-" : obj.getObjUserPerformance() + " ~ " + obj.getToUserPerformance() == null ? "-" : obj.getToUserPerformance();
                    // 1待生效、2进行中、3已完成、4已失效
                    if (obj.getState() != null) {
                        if (obj.getState() == 1) {
                            values[i][10] = "待生效";
                        } else if (obj.getState() == 2) {
                            values[i][10] = "进行中";
                        } else if (obj.getState() == 3) {
                            values[i][10] = "已完成";
                        } else if (obj.getState() == 4) {
                            values[i][10] = "已失效";
                        } else {
                            values[i][10] = "";
                        }
                    } else {
                        values[i][10] = "";
                    }
                    if (obj.getResult() != null) {
                        if (obj.getResult() == 1) {
                            values[i][11] = "输";
                        } else if (obj.getResult() == 2) {
                            values[i][11] = "赢";
                        } else if (obj.getResult() == 3) {
                            values[i][11] = "平";
                        } else if (obj.getResult() == 4) {
                            values[i][11] = "待定";
                        } else {
                            values[i][11] = "";
                        }
                    } else {
                        values[i][11] = "";
                    }
                }
            }
            outPutExcel(response, title, fileName, sheetName, values);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 输出Excel
     *
     * @param response
     * @param title
     * @param fileName
     * @param sheetName
     * @param values
     * @throws IOException
     */
    private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
        // 创建HSSFWorkbook
        HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        // 将文件存到指定位置
        this.setResponseHeader(response, fileName);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 发送响应流方法
     *
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
        }
    }

    /**
     * 查询组织下的部门
     *
     * @param code
     * @param list
     * @throws Exception
     */
    private void selectSonId(String code, List<String> list) throws Exception {
        List<Dept> deptList = this.deptService.selectByParentCode(code);
        if (deptList != null) {
            for (Dept dept1 : deptList) {
                list.add(dept1.getId());
                selectSonId(dept1.getCode(), list);
            }
        }
    }

    /**
     * 查询组织下的部门
     *
     * @param code
     * @param list
     * @throws Exception
     */
    private void selectSonId1(String code, List<String> list) throws Exception {
        Dept dept = this.deptService.selectByCode(code);
        List<Dept> deptList = this.deptService.selectByParentCode(code);
        if (deptList != null && deptList.size() > 0) {
            for (Dept dept1 : deptList) {
                list.add(dept1.getId());
                selectSonId1(dept1.getCode(), list);
            }
        } else {
            if (dept != null) {
                list.add(dept.getId());
            }
        }

    }

    /**
     * 删除重复项
     *
     * @param list
     * @return
     */
    private List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


}
